package com.wanmait.schedule.controller;

import com.wanmait.schedule.entity.Permission;
import com.wanmait.schedule.entity.Teacher;
import com.wanmait.schedule.service.PermissionService;
import com.wanmait.schedule.shiro.ShiroRealm;
import com.wanmait.schedule.util.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 权限表 前端控制器
 * </p>
 *
 * @author wanmait
 * @since 2022-12-05
 */
@RestController
@RequestMapping("/manage/permission")
@RequiresPermissions("manage:role_permission")
public class PermissionController {
    @Resource
    private PermissionService permissionService;
    //添加
    @PostMapping("insert")
    public AjaxResult insert(@RequestBody Permission permission,HttpServletRequest request){
        Teacher teacher = (Teacher) request.getAttribute("teacher");
        permission.setInputId(teacher.getId());
        permissionService.save(permission);
        return AjaxResult.success("添加成功");
    }
    //修改
    @PostMapping("update")
    public AjaxResult update(@RequestBody Permission permission){
        permissionService.updateById(permission);

        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        ShiroRealm shiroRealm = (ShiroRealm) securityManager.getRealms().iterator().next();
        shiroRealm.clearCached();

        return AjaxResult.success("成功");
    }
    //列表
    @GetMapping("list")
    public AjaxResult list(){
        return AjaxResult.success(permissionService.list());
    }
    //删除
    @GetMapping("delete")
    public AjaxResult delete(Integer id){
        permissionService.removeById(id);
        return AjaxResult.success("删除成功");
    }
}
